#include "Widget.h"
#include "ui_widget.h"
#include <QPainter>
#include <QFileDialog>
#include <QDebug>
#include <QKeyEvent>
#include <QTimer>
#include <QMouseEvent>
#include <cmath>

extern GameMap* gameMap;
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("Tank 2022");
    mypainter = new QPainter;
    gameMap = new GameMap(this);
    player1 = new Tank(Qt::Key_W,Qt::Key_S,Qt::Key_A,Qt::Key_D,this);
    player2 = new Tank(Qt::Key_Up,Qt::Key_Down,Qt::Key_Left,Qt::Key_Right,this);
    timer=new QTimer(this);
    timer->start(100);
    connect(timer,&QTimer::timeout,[this](){update();});
    QString filename = QFileDialog::getOpenFileName(this,"选择地图文件","./","*.txt");
    gameMap->iniByTxt(filename);
    this->setMouseTracking(true);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::DrawMap()
{
    for(int i=0;i<gameMap->row;i++)
    {
        for(int j=0;j<gameMap->col;j++)
        {
            QString imageUrl;
            switch(gameMap->Gmap[i][j])
            {
            case road:imageUrl=":/map_image/element/road.png";break;
            case wall:imageUrl=":/map_image/element/wall.gif";break;
            case grass:imageUrl=":/map_image/element/grass.gif";break;
            }
            QImage image(imageUrl);
            mypainter->drawImage(QRectF(j*image.width(),i*image.height(),image.width(),image.height()),image);
        }
    }
}

void Widget::paintEvent(QPaintEvent* event)
{
    Q_UNUSED(event);
    mypainter->begin(this);
    DrawMap();
    player1->DrawTank(mypainter,player1->mydir);
    player2->DrawTank(mypainter,player2->mydir);
    mypainter->end();
}

void Widget::keyPressEvent(QKeyEvent *event)
{
    player1->HowMove(event);
    player2->HowMove(event);
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    //实现player2方向跟随鼠标光标
    QPoint TankVector=QPoint(event->pos().x()-player2->pos_x,event->pos().y()-player2->pos_y);
    if(TankVector.x()>0 && TankVector.x() >= abs(TankVector.y()))
    {
        player2->mydir = xright;
    }
    else if(TankVector.x()<0 && -TankVector.x() >= abs(TankVector.y()))
    {
        player2->mydir = xleft;
    }
    else if(TankVector.y()>0 && TankVector.y() >= abs(TankVector.x()))
    {
        player2->mydir = xdown;
    }
    else if(TankVector.y()<0 && -TankVector.y() >= abs(TankVector.x()))
    {
        player2->mydir = xup;
    }
}
